﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Timers;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using uclock.ClockClass;
using uclock.Model;
using uclock.ViewModel;

namespace uclock
{
    public class MainViewModel : ViewModelBase
    {

        private TimeSplit _timeSplit;
        private readonly ClockAddViewModel _clockAddViewModel;
        public TimeSplit TimeSplit 
        {
            get { return _timeSplit; }
            set
            {
                if (_timeSplit != value) // 防止无必要的UI通知
                {
                _timeSplit = value;
                RaisePropertyChanged("TimeSplit");
                }
            }
        }


        public MainViewModel()
        {
            _clockAddViewModel = ViewModelLocator.ClockAddStatic;
            var aTimer = new Timer()
            {
                Interval = 1000.0,
                Enabled = true,
            };
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        }


        private bool _issencond = true; 
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            _issencond = !_issencond;
            var dateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            TimeSplit = new TimeSplit()
                {
                    Y1 = dateTime[0],
                    Y2 = dateTime[1],
                    Y3 = dateTime[2],
                    Y4 = dateTime[3],
                    M1 = dateTime[4],
                    M2 = dateTime[5],
                    D1 = dateTime[6],
                    D2 = dateTime[7],
                    H1 = dateTime[8],
                    H2 = dateTime[9],
                    Mi1 = dateTime[10],
                    Mi2 = dateTime[11],
                    S1 = dateTime[12],
                    S2 = dateTime[13],
                    Her = _issencond ? ' ' : '-',
                    Piont = !_issencond ? ' ' : ':'
                };

            foreach (var recored in _clockAddViewModel.DateTimeClocks)
            {
                if (recored.ClockDate == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                {
                    if (recored.Music)
                    {
                        MusicPlayer.Execute(null);
                    }

                    if (recored.Beer)
                    {
                        BeepVulous.Beep(1000, 1000);
                    }

                    if (recored.Email)
                    {
                        EmailSend.Send(recored.EmailAdress,recored.RecordConent);
                    }
                }
            }

        }

        public ICommand MusicPlayer { get; set; }


        public override void Cleanup()
        {
            // Clean own resources if needed

            base.Cleanup();
        }
    }
}